package com.xiaoyang.controller;

import com.xiaoyang.dto.ResultDTO;
import com.xiaoyang.dto.UserDTO;
import com.xiaoyang.helper.DateHelper;
import com.xiaoyang.mapper.UserMapper;
import com.xiaoyang.service.AutoLocationService;
import com.xiaoyang.service.UserService;
import com.xiaoyang.service.WxPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author guoziyang
 * @create 2020/9/21 12:28 下午
 */
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private AutoLocationService autoLocationService;

    @Autowired
    private UserService userService;

    @Autowired
    private WxPushService wxPushService;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public ResultDTO login(@RequestBody UserDTO userDTO) {
        String cookie = autoLocationService.getCookie(userDTO.getUsername(), userDTO.getPassword());
        if (cookie == null) {
            return new ResultDTO(0, "账号或密码错误");
        }
        // 用户是否存在
        Boolean isUserExist = userService.isUserExist(userDTO.getUsername());
        if (isUserExist) {
            return new ResultDTO(1, "用户已存在");
        }
        // 获取真实姓名
        String realName = userService.getRealName(userDTO);
        // 保存用户信息
        userDTO.setRealName(realName);
        ResultDTO resultDTO = userService.saveUserInfo(userDTO);
        // 微信推送
        String message = realName + "同学您在" + DateHelper.getCurrentTime() + "成功登陆今日校园！";
        wxPushService.wxPush(message, "UID_" + userDTO.getUid());
        wxPushService.wxPush(message, "UID_iAB4BFMt7quFBtA4eFOeQl117fbZ");
        return resultDTO;
    }

}
